package com.abc.recycling.service.impl;

import com.abc.recycling.model.Order;
import com.abc.recycling.repository.OrderRepository;
import com.abc.recycling.service.CollectorOrderService;
import com.abc.recycling.service.EvaluationService;
import com.abc.recycling.service.NotificationService;
import com.abc.recycling.service.MessageService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.math.BigDecimal;

@Slf4j
@Service
@RequiredArgsConstructor
public class CollectorOrderServiceImpl implements CollectorOrderService {

    private final OrderRepository orderRepository;
    private final EvaluationService evaluationService;
    private final NotificationService notificationService;
    private final MessageService messageService;

    @Override
    public Page<Order> getOrdersByCollectorId(Long collectorId, Pageable pageable) {
        try {
            return orderRepository.findByCollectorId(collectorId, pageable);
        } catch (Exception e) {
            log.error("获取回收员订单失败: {}", e.getMessage());
            return new PageImpl<>(new ArrayList<>(), pageable, 0);
        }
    }

    @Override
    public Page<Order> getOrdersByCollectorAndStatus(Long collectorId, String status, Pageable pageable) {
        try {
            return orderRepository.findByCollectorIdAndStatus(collectorId, status, pageable);
        } catch (Exception e) {
            log.error("获取回收员状态订单失败: {}", e.getMessage());
            return new PageImpl<>(new ArrayList<>(), pageable, 0);
        }
    }

    @Override
    public long countOrdersByCollector(Long collectorId) {
        try {
            return orderRepository.countByCollectorId(collectorId);
        } catch (Exception e) {
            log.error("统计回收员订单数失败: {}", e.getMessage());
            return 0L;
        }
    }

    @Override
    public long countCompletedOrdersByCollector(Long collectorId) {
        try {
            return orderRepository.countByCollectorIdAndStatus(collectorId, "COMPLETED");
        } catch (Exception e) {
            log.error("统计回收员完成订单数失败: {}", e.getMessage());
            return 0L;
        }
    }

    @Override
    public long countOrdersByCollectorAndStatus(Long collectorId, String status) {
        try {
            return orderRepository.countByCollectorIdAndStatus(collectorId, status);
        } catch (Exception e) {
            log.error("统计回收员状态订单数失败: {}", e.getMessage());
            return 0L;
        }
    }

    @Override
    public double getCollectorMonthlyIncome(Long collectorId) {
        try {
            LocalDateTime monthStart = LocalDateTime.now().withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
            return orderRepository.sumPriceByCollectorIdAndCreateTimeAfter(collectorId, monthStart);
        } catch (Exception e) {
            log.error("获取回收员月收入失败: {}", e.getMessage());
            return 0.0;
        }
    }

    @Override
    public double getCollectorTotalWeight(Long collectorId) {
        try {
            return orderRepository.sumWeightByCollectorId(collectorId);
        } catch (Exception e) {
            log.error("获取回收员总重量失败: {}", e.getMessage());
            return 0.0;
        }
    }

    @Override
    public List<Map<String, Object>> getOrderTrendByCollector(Long collectorId) {
        try {
            LocalDateTime endDate = LocalDateTime.now();
            LocalDateTime startDate = endDate.minusDays(30);
            return orderRepository.getOrderTrendByCollector(collectorId, startDate, endDate);
        } catch (Exception e) {
            log.error("获取回收员订单趋势失败: {}", e.getMessage());
            return new ArrayList<>();
        }
    }

    @Override
    public Map<String, Long> getItemDistributionByCollector(Long collectorId) {
        try {
            List<Map<String, Object>> distribution = orderRepository.getItemDistributionByCollector(collectorId);
            Map<String, Long> result = new HashMap<>();
            for (Map<String, Object> item : distribution) {
                String type = (String) item.get("type");
                Long count = ((Number) item.get("count")).longValue();
                result.put(type, count);
            }
            return result;
        } catch (Exception e) {
            log.error("获取回收员物品分布失败: {}", e.getMessage());
            return new HashMap<>();
        }
    }

    @Override
    public Map<String, Long> getCollectorOrderStats(Long collectorId) {
        try {
            Map<String, Object> stats = orderRepository.getCollectorOrderStats(collectorId);
            Map<String, Long> result = new HashMap<>();
            
            // 转换键名为驼峰命名
            if (stats.containsKey("total_orders")) {
                result.put("totalOrders", ((Number) stats.get("total_orders")).longValue());
            }
            if (stats.containsKey("completed_orders")) {
                result.put("completedOrders", ((Number) stats.get("completed_orders")).longValue());
            }
            if (stats.containsKey("monthly_orders")) {
                result.put("monthlyOrders", ((Number) stats.get("monthly_orders")).longValue());
            }
            if (stats.containsKey("monthly_completed_orders")) {
                result.put("monthlyCompletedOrders", ((Number) stats.get("monthly_completed_orders")).longValue());
            }
            if (stats.containsKey("pending_orders")) {
                result.put("pendingOrders", ((Number) stats.get("pending_orders")).longValue());
            }
            if (stats.containsKey("processing_orders")) {
                result.put("processingOrders", ((Number) stats.get("processing_orders")).longValue());
            }
            
            return result;
        } catch (Exception e) {
            log.error("获取回收员订单统计失败: {}", e.getMessage());
            return new HashMap<>();
        }
    }

    @Override
    public Map<String, Object> getCollectorEvaluationStats(Long collectorId) {
        try {
            Map<String, Object> stats = new HashMap<>();
            
            // 获取评分统计
            Double avgRating = evaluationService.getCollectorAverageRating(collectorId);
            Long totalEvaluations = evaluationService.getCollectorEvaluationCount(collectorId);
            List<Integer> ratingDistribution = evaluationService.getCollectorRatingDistribution(collectorId);
            
            // 计算好评率（4星及以上）
            long goodRatings = 0;
            if (ratingDistribution != null && ratingDistribution.size() >= 2) {
                // 4星和5星的评价数量
                goodRatings = ratingDistribution.get(ratingDistribution.size() - 1) + 
                             ratingDistribution.get(ratingDistribution.size() - 2);
            }
            double goodRatePercent = totalEvaluations > 0 
                    ? (double) goodRatings / totalEvaluations * 100 
                    : 0.0;
            
            // 获取订单完成情况
            long totalOrders = orderRepository.countByCollectorId(collectorId);
            long completedOrders = orderRepository.countByCollectorIdAndStatus(collectorId, "COMPLETED");
            double completionRate = totalOrders > 0 
                    ? (double) completedOrders / totalOrders * 100 
                    : 0.0;
            
            // 获取月度统计
            LocalDateTime monthStart = LocalDateTime.now().withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
            long monthlyOrders = orderRepository.countByCollectorIdAndCreateTimeAfter(collectorId, monthStart);
            long monthlyCompletedOrders = orderRepository.countByCollectorIdAndStatusAndCreateTimeAfter(
                    collectorId, "COMPLETED", monthStart);
            
            // 填充统计数据
            stats.put("averageRating", avgRating != null ? avgRating : 0.0);
            stats.put("totalEvaluations", totalEvaluations != null ? totalEvaluations : 0L);
            stats.put("ratingDistribution", ratingDistribution);
            stats.put("goodRatePercent", goodRatePercent);
            stats.put("completionRate", completionRate);
            stats.put("totalOrders", totalOrders);
            stats.put("completedOrders", completedOrders);
            stats.put("monthlyOrders", monthlyOrders);
            stats.put("monthlyCompletedOrders", monthlyCompletedOrders);
            
            return stats;
        } catch (Exception e) {
            log.error("获取回收员评价统计失败: {}", e.getMessage());
            return new HashMap<>();
        }
    }

    @Override
    public Page<Order> getCollectorOrderHistory(Long collectorId, Pageable pageable) {
        try {
            return orderRepository.findByCollectorIdOrderByCreateTimeDesc(collectorId, pageable);
        } catch (Exception e) {
            log.error("获取回收员订单历史失败: {}", e.getMessage());
            return new PageImpl<>(new ArrayList<>(), pageable, 0);
        }
    }

    @Override
    public long countOrdersByCollectorAndDate(Long collectorId, LocalDateTime date) {
        try {
            return orderRepository.countByCollectorIdAndCreateTimeAfter(collectorId, date);
        } catch (Exception e) {
            log.error("统计回收员日期订单数失败: {}", e.getMessage());
            return 0L;
        }
    }

    @Override
    public Page<Order> getOrdersByStatus(String status, Pageable pageable) {
        try {
            return orderRepository.findByStatus(status, pageable);
        } catch (Exception e) {
            log.error("获取状态订单失败: {}", e.getMessage());
            return new PageImpl<>(new ArrayList<>(), pageable, 0);
        }
    }

    @Override
    public boolean acceptOrder(Long orderId, Long collectorId) {
        try {
            Order order = orderRepository.findById(orderId).orElse(null);
            if (order == null || !order.getStatus().equals("PENDING")) {
                return false;
            }
            
            order.setCollectorId(collectorId);
            order.setStatus("PROCESSING");
            order.setUpdateTime(LocalDateTime.now());
            orderRepository.save(order);
            return true;
        } catch (Exception e) {
            log.error("接受订单失败: {}", e.getMessage());
            return false;
        }
    }

    @Override
    public boolean completeOrder(Long orderId, Long collectorId, Double actualWeight, Double price) {
        try {
            Order order = orderRepository.findById(orderId).orElse(null);
            if (order == null || !order.getStatus().equals("PROCESSING") || !order.getCollectorId().equals(collectorId)) {
                return false;
            }
            
            order.setActualWeight(actualWeight);
            order.setPrice(new BigDecimal(price.toString()));
            order.setStatus("COMPLETED");
            order.setCompleteTime(LocalDateTime.now());
            order.setUpdateTime(LocalDateTime.now());
            orderRepository.save(order);

            // 发送订单完成消息给用户
            Map<String, Object> params = new HashMap<>();
            params.put("orderNo", order.getOrderNo());
            params.put("actualWeight", String.format("%.1f", actualWeight));
            params.put("price", String.format("%.2f", price));
            messageService.sendMessageWithTemplate("ORDER_COMPLETED", order.getUserId(), params);
            
            return true;
        } catch (Exception e) {
            log.error("完成订单失败: {}", e.getMessage());
            return false;
        }
    }

    @Override
    public long countOrdersByStatus(String status) {
        try {
            return orderRepository.countByStatus(status);
        } catch (Exception e) {
            log.error("统计状态订单数失败: {}", e.getMessage());
            return 0L;
        }
    }
} 